package com.sundablog.controller.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


import com.sundablog.pojo.AdminUser;
import com.sundablog.pojo.AdminUserRole;
import com.sundablog.pojo.AdminUserRoleExample;
import com.sundablog.service.systemsetup.permissionsManage.permissions.PermissionsService;
import com.sundablog.service.systemsetup.permissionsManage.role.RoleService;
import com.sundablog.service.systemsetup.permissionsManage.user.UserService;
import com.sundablog.utlis.RedisUtil;

import cn.hutool.core.util.StrUtil;

public class BackendRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private PermissionsService permissionsService;
	
	// 认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;
		// 获得页面输入的用户名
		String username = passwordToken.getUsername();
		// 根据用户名查询数据库中的密码
		AdminUser adminUser = userService.selectByUserName(username);
		if (adminUser == null) {
			// 页面输入的用户名不存在
			return null;
		}
		// 简单认证信息对象
		AuthenticationInfo info = new SimpleAuthenticationInfo(adminUser, adminUser.getPassword(), this.getName());
		return info;
	}

	// 授权方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		AdminUser user = (AdminUser) SecurityUtils.getSubject().getPrincipal();
		
		String backend_reaim = RedisUtil.get("backend_reaim_"+user.getUserId());
		if (null == backend_reaim || "".equals(backend_reaim)) {
			//获取当前登录用户对象
			
			AdminUserRole userRole = roleService.selectByUserId(user.getUserId());
			List<String> list = permissionsService.selectByRoleId(userRole.getRoleId());
			String join = StrUtil.join(",", list);
			RedisUtil.set("backend_reaim_"+user.getUserId(), join, RedisUtil.EXRP_HOUR);
			
			for (String string : list) {
				info.addStringPermission(string);
			}
			return info;
		} else {
			
			
			String[] split = StrUtil.split(backend_reaim, ",");
			for (String string : split) {
				info.addStringPermission(string);
			}
			return info;
		}
	}

}
